import React from 'react';
import PropTypes from 'prop-types';
import TimePicker from 'rc-time-picker';
import dayjs from 'dayjs';

import 'rc-time-picker/assets/index.css';
import cn from 'classnames';
import {
	CloseFilled16 as ClearIcon,
	Time16 as TimeIcon,
} from '@carbon/icons-react';

import s from './TimeRangePicker.module.css';

const createMoment = timestr => {
	if (typeof timestr !== 'string') return timestr;
	const timeArr = timestr.split(':');
	return dayjs()
		.hour(parseInt(timeArr[0]))
		.minute(parseInt(timeArr[1]))
		.second(parseInt(timeArr[2]));
};

function TimeRangePicker({
	className,
	value = { start: undefined, end: undefined },
	onChange,
}) {
	const handleChange = ({ start, end }) =>
		onChange({
			start: start?.format ? start.format('HH:mm:ss') : start,
			end: end?.format ? end.format('HH:mm:ss') : end,
		});
	return (
		<div className={cn(className, s.timeRangePicker)}>
			<TimePicker
				className={s.timePicker}
				showSecond={false}
				inputIcon={<TimeIcon className={s.timeIcon} />}
				clearIcon={<ClearIcon className={s.clearIcon} />}
				defaultValue={value.start ? createMoment(value.start) : value.start}
				value={value.start ? createMoment(value.start) : value.start}
				onChange={val => handleChange({ ...value, start: val })}
			/>
			<span> ~ </span>
			<TimePicker
				className={s.timePicker}
				showSecond={false}
				inputIcon={<TimeIcon className={s.timeIcon} />}
				clearIcon={<ClearIcon className={s.clearIcon} />}
				value={value.end ? createMoment(value.end) : value.end}
				defaultValue={value.end ? createMoment(value.end) : value.end}
				onChange={val => handleChange({ ...value, end: val })}
			/>
		</div>
	);
}

TimeRangePicker.propTypes = {
	className: PropTypes.string,
	value: PropTypes.shape({
		start: PropTypes.date,
		end: PropTypes.date,
	}).isRequired,
	onChange: PropTypes.func,
};
TimeRangePicker.defaultProps = {
	className: s.timeRangePicker,
	onChange: () => {},
};

export default TimeRangePicker;
